package com.ysd.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ysd.gulimall.member.dao.MemberLevelDao;
import com.ysd.gulimall.member.entity.MemberLevelEntity;
import com.ysd.gulimall.member.util.HttpUtils;
import com.ysd.gulimall.member.vo.MemberLoginVo;
import com.ysd.gulimall.member.vo.MemberRegistVo;
import com.ysd.gulimall.member.vo.SocialUser;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.utils.PageUtils;
import com.ysd.common.utils.Query;

import com.ysd.gulimall.member.dao.MemberDao;
import com.ysd.gulimall.member.entity.MemberEntity;
import com.ysd.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<MemberEntity> memberEntityQueryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)){
            memberEntityQueryWrapper.like("username", key)
                    .or().like("level_id", key).like("nickname", key);
        }

        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                memberEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {

        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));

        //判断是否登录成功
        if (entity ==null){

            return null;
            //fail
        }else{
            //判断密码
            String password1 = entity.getPassword();
            if (password.equals(password1)){
                return entity;
            }else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //具有登录和注册逻辑
        //获取用户的uid
        String uid = socialUser.getUid();
        //判断该社交账号是否登录过本系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity != null){
            //该账号登录过本系统，修改该用户的accesstoken和过期时间
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccess_token(socialUser.getAccess_token());
            update.setExpires_in(socialUser.getExpires_in());

            memberDao.updateById(update);

            memberEntity.setExpires_in(socialUser.getExpires_in());
            memberEntity.setAccess_token(socialUser.getAccess_token());

            return memberEntity;

        }else {
            //该账号没有登录过,注册一个
            MemberEntity regist = new MemberEntity();
            try {
                //查询当前社交账号的信息（昵称、性别等）
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

                if (response.getStatusLine().getStatusCode() == 200){
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject object = JSON.parseObject(json);

                    String name = object.getString("name");
                    String gender = object.getString("gender");

                    regist.setNickname(name);
                    regist.setGender("m".equals(gender)?1:0);

                }
            }catch (Exception e){}
            regist.setSocial_uid(socialUser.getUid());
            regist.setAccess_token(socialUser.getAccess_token());
            regist.setExpires_in(socialUser.getExpires_in());
            memberDao.insert(regist);
            return regist;
        }
    }

}